package com.dzl.config.database;


import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(1)
public class DataSourceAop {

//    @Pointcut("!@annotation(org.dzl.config.database.Master) " +
//            "&& (execution(* org.dzl..service..*.get*(..))) " +
//            "|| execution(* org.dzl..service..*.select*(..)))"+
//            "|| execution (* org.dzl..service..*.select*(..)))")
//    public void readPointcut() {
//
//    }
//
//    @Pointcut("@annotation(org.dzl.config.database.Master) " +
//            "|| execution(* org.dzl..service..*.insert*(..)) " +
//            "|| execution(* org.dzl..service..*.add*(..)) " +
//            "|| execution(* org.dzl..service..*.update*(..)) " +
//            "|| execution(* org.dzl..service..*.edit*(..)) " +
//            "|| execution(* org.dzl..service..*.delete*(..)) " +
//            "|| execution(* org.dzl..service..*.remove*(..))")
//    public void writePointcut() {
//
//    }
//
//    @Before("readPointcut()")
//    public void read() {
//        DBContextHolder.slave();
//    }
//
//    @Before("writePointcut()")
//    public void write() {
//        DBContextHolder.master();
//    }


	/**
	 * 另一种写法：if...else...  判断哪些需要读从数据库，其余的走主数据库
	 */
    @Before("execution(* com.dzl..service.impl.*.*(..))&&!@annotation(com.dzl.config.database.Master)")
    public void before(JoinPoint jp) {
        String methodName = jp.getSignature().getName();

        if (StringUtils.startsWithAny(methodName, "get", "select", "find","go","query")) {
            DBContextHolder.slave();
        }else {
            DBContextHolder.master();
        }
    }
    /**
     *
     * @Description:master注解 走主库
     * @param jp
     * void
     * @exception:
     * @author: liufan
     * @time:2019年12月6日 上午10:28:31
     */
    @Before("@annotation(com.dzl.config.database.Master)")
    public void annotationMaster(JoinPoint jp) {
		DBContextHolder.master();
    }
}
